package com.ruigi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruigi.Exception.Customexception;
import com.ruigi.mapper.Categorymapper;
import com.ruigi.pojo.Category;
import com.ruigi.pojo.Dish;
import com.ruigi.pojo.R;
import com.ruigi.pojo.Setmeal;
import com.ruigi.service.CategoryService;
import com.ruigi.service.Dishservice;
import com.ruigi.service.Setmealservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class Categoryimpl extends ServiceImpl<Categorymapper, Category> implements CategoryService {
    @Autowired
    private Dishservice dishservice;
    @Autowired
    private Setmealservice setmealservice;

    @Override
    public R<String> save1(Category category) {

        save(category);


        return R.success("成功！");
    }

    @Override
    public R<Page> page1(int page, int pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<Category>();
        queryWrapper.orderByAsc(Category::getSort);
        page(categoryPage, queryWrapper);
        return R.success(categoryPage);
    }

    @Override
    public R<String> delete(Long ids) {
        removeById(ids);

        return R.success("成功！");
    }

    @Override
    public void remove(Long ids) {
        LambdaQueryWrapper<Dish> deryWrapper = new LambdaQueryWrapper<>();
        deryWrapper.eq(Dish::getCategoryId, ids);
        int count = dishservice.count(deryWrapper);
        if (count > 0) {
            //有关联的菜品数据
            throw new Customexception("当前分类下关联了菜品，不能删除");

        }
        LambdaQueryWrapper<Setmeal> setQueryWrapper = new LambdaQueryWrapper<>();
        setQueryWrapper.eq(Setmeal::getCategoryId, ids);
        int count2 = setmealservice.count(setQueryWrapper);
        if (count2 > 0) {
            //有关联的套餐数据
            throw new Customexception("当前分类下关联了套餐，不能删除");


        }
        super.removeById(ids);


    }

    @Override
    public R<String> update(Category category) {

        super.updateById(category);


        return R.success("修改分类成功！");
    }

    @Override
    public R<List<Category>> type(Category category) {

        LambdaQueryWrapper<Category> ambdaQueryWrapper = new LambdaQueryWrapper<Category>();
        ambdaQueryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        ambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = super.list(ambdaQueryWrapper);


        return R.success(list);
    }

}
